package com.lechuang.gateway.filter;

import com.alibaba.nacos.shaded.com.google.common.collect.Lists;
import com.lechuang.gateway.constant.Constant;
import com.lechuang.gateway.model.WhiteListDefine;
import com.lechuang.gateway.properties.RouterProperties;
import com.lechuang.gateway.properties.WhitelistProperties;
import com.lechuang.gateway.util.ExchangeUtils;
import jakarta.annotation.Resource;
import lombok.extern.log4j.Log4j2;
import org.springframework.cloud.gateway.filter.FilterDefinition;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.RouteDefinition;
import org.springframework.core.Ordered;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * </p>
 *
 * @author liaoningbo
 * @since 2024-01-08
 */
@Component
@Log4j2
public class PathWhiteListFilter implements GlobalFilter, Ordered {
    @Resource
    private RouterProperties routerProperties;
    @Resource
    private WhitelistProperties whitelistProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("开始请求路径白名单校验");
        //判断是否跳过当前校验
        if (ExchangeUtils.isSkip(exchange)) {
            return chain.filter(exchange);
        }
        ServerHttpRequest request = exchange.getRequest();
        //获取请求path
        String path = request.getPath().toString();
        boolean isWhitePath = this.isWhitelistPath(path);
        //如果白名单内，后续校验跳过
        if (isWhitePath){
            log.info("请求路径在白名单中，后续校验直接跳过");
            ExchangeUtils.setSkip(exchange);
            return chain.filter(exchange);
        }else {
            log.info("请求路径:{}不在白名单内，继续执行后续的校验", path);
            return chain.filter(exchange);
        }
    }

    @Override
    public int getOrder() {
        return Constant.PATH_FILTER_ORDER;
    }

    /**
     * 匹配接口白名单规则
     * @param path
     * @return
     */
    public Boolean isWhitelistPath(String path){
        //根据请求path，获取对应的routeId
        String routeId = routerProperties.getIdByRequestPath(path);
        //如果routeId为空，说明该请求path匹配不到对应的路由，直接返回false
        if(StringUtils.isEmpty(routeId)){
            return false;
        }
        //白名单列表
        List<String> values = this.getPathWhiteListById(routeId);
        if (values.size() == 0){
            return false;
        }else {
            //获取StripPrefix的参数值
            Integer stripPrefix = this.getStripPrefix(routeId);
            //截取请求path
            path = path.substring(path.indexOf("/",stripPrefix));
            //path匹配接口白名单规则
            return this.matchRequestPath(values, path);
        }
    }

    /**
     * <p>
     *     获取白名单列表
     * </p>
     * @author liaoningbo
     * @since 2024/1/8
     */
    public List<String> getPathWhiteListById(String routeId) {
        List<String> pathWhite = new ArrayList<>();
        //获取配置文件中的ip白名单列表
        for (WhiteListDefine ipWhitelistDefine : whitelistProperties.getPathWhiteList()) {
            //如果该请求的routeId存在，需要获取routeId下的ip列表
            if (ipWhitelistDefine.getId().equals(routeId)){
                pathWhite = ipWhitelistDefine.getList();
                break;
            }
        }
        return pathWhite;
    }

    /**
     * <p>
     *     获取StripPrefix的参数值
     * </p>
     * @author liaoningbo
     * @since 2024/1/8
     */
    public Integer getStripPrefix(String routeId){
        //根据routeId匹配
        RouteDefinition routeDefinition = routerProperties.getRoutes().stream().filter(l -> l.getId().equals(routeId)).collect(Collectors.toList()).get(0);
        Integer stripPrefix = 0;
        //获取StripPrefix的参数值
        for (FilterDefinition filter : routeDefinition.getFilters()) {
            if ("StripPrefix".equals(filter.getName())){
                Collection<String> values = filter.getArgs().values();
                stripPrefix = values.size() > 0 ? Integer.parseInt(Lists.newArrayList(values).get(0)) : 0;
            }
        }
        return stripPrefix;
    }

    /**
     * <p>
     *     校验path是否在接口白名单内
     * </p>
     * @author liaoningbo
     * @since 2024/1/8
     */
    private boolean matchRequestPath(List<String> patterns, String requestPath){
        boolean isMatch = false;
        for (String pattern : patterns){
            isMatch = routerProperties.matchPath(pattern, requestPath);
            if (isMatch){
                break;
            }
        }
        return isMatch;
    }
}
